var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');

var indexPath = path.join(__dirname, '../public/index.json');
var readFile = function (key, file) {
  return JSON.parse(fs.readFileSync(path.join(__dirname, '../public/' + key + '/' + file + '.json'), 'utf-8'));
}

var writeFile = function (key, file, data) {
  fs.writeFileSync(path.join(__dirname, '../public/' + key + '/' + file + '.json'), data);
}

/* GET home page. */
router.get('/GetApps', function (req, res, next) {
  var json = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
  res.send(json);
});

router.get('/GetApp/:key', function (req, res, next) {
  var key = req.params.key;
  var config = readFile(key, 'config');
  var index = readFile(key, 'index');
  res.send({
    config,
    index,
  });
});

router.post('/CreateApp', function (req, res, next) {
  var key = req.body.key;
  var Folder = path.join(__dirname, '../public/' + key);

  fs.access(Folder, function (error, msg) {
    if (error) {
      fs.mkdirSync(Folder);

      var icon = req.body.icon;
      icon = icon.replace(/^data:image\/\w+;base64,/, "");
      var iconBuffer = Buffer.from(icon, 'base64');
      fs.writeFileSync(path.join(__dirname, '../public/' + key + '/icon.png'), iconBuffer);

      var lastVersion = req.body.version[0].version;
      var lastVersionFile = req.body.version[0].file;
      var lastVersionFileBuffer = Buffer.from(lastVersionFile, 'base64');
      fs.writeFileSync(path.join(__dirname, '../public/' + key + '/' + key + '-v' + lastVersion + '.zip'), lastVersionFileBuffer);


      var config = {
        "index": "index.html",
        "minWidth": 1280,
        "minHeight": 800,
        "title": key,
        "key": key,
        "name": req.body.title,
        "localVersion": lastVersion,
        "icon": "icon.png"
      };
      writeFile(key, 'config', JSON.stringify(config));


      var index = [];
      for (let i = 0; i < req.body.version.length; i++) {
        const element = req.body.version[i];
        var data = {
          "date": element.date,
          "debug": element.debug,
          "update": element.update,
          "FileName": key + '-v' + lastVersion + '.zip',
          "version": element.version,
        };
        index.push(data);
      }
      writeFile(key, 'index', JSON.stringify(index));


      var _json = {
        "key": req.body.key,
        "path": "/" + req.body.key + "/index.json",
        "title": req.body.title,
        "description": req.body.description,
        "icon": "/" + req.body.key + "/icon.png",
        "lastVersion": lastVersion,
      }
      var json = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
      json.push(_json);
      fs.writeFileSync(indexPath, JSON.stringify(json));

      // 创建成功
      res.send(true);

    } else {
      res.status(500).send('已经存在APP');
    }
  });
})


router.post('/AddVersion/:key', function (req, res, next) {
  var key = req.params.key;

  var lastVersion = req.body.version;
  var lastVersionFile = req.body.file;
  var lastVersionFileBuffer = Buffer.from(lastVersionFile, 'base64');
  fs.writeFileSync(path.join(__dirname, '../public/' + key + '/' + key + '-v' + lastVersion + '.zip'), lastVersionFileBuffer);


  var json = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
  for (let i = 0; i < json.length; i++) {
    const element = json[i];
    if (element.key == key) {
      element.lastVersion = lastVersion;
      break;
    }
  }
  fs.writeFileSync(indexPath, JSON.stringify(json));

  var index = readFile(key, 'index');
  index.unshift({
    "date": req.body.date,
    "debug": req.body.debug,
    "update": req.body.update,
    "FileName": key + '-v' + lastVersion + '.zip',
    "version": lastVersion,
  })
  writeFile(key, 'index', JSON.stringify(index));

  var config = readFile(key, 'config');
  config.localVersion = lastVersion;
  writeFile(key, 'config', JSON.stringify(config));

  // 创建成功
  res.send(true);
})


module.exports = router;